<template>
  <view class="order-list-page">
    <!-- 顶部导航栏 -->
    <view class="shop-header">
      <view class="header-content">
        <view class="back-btn" @click="navigateBack">
          <image class="back-icon" src="/static/Images/shop/Fanhuih.png" mode="aspectFit"></image>
        </view>
        <view class="title">我的抢单</view>
      </view>
    </view>
    
    <!-- 商品类型标签 -->
    <view class="product-type-tabs">
      <view 
        v-for="(type, index) in productTypes" 
        :key="index"
        class="type-tab" 
        :class="{active: activeProductType === type.value}" 
        @click="switchProductType(type.value)"
      >
        {{ type.label }}
      </view>
    </view>
    
    <!-- 订单状态标签 -->
    <view class="status-tabs">
      <view class="tab" :class="{active: activeTab === 'all'}" @click="switchTab('all')">全部</view>
      <view class="tab" :class="{active: activeTab === 'trading'}" @click="switchTab('trading')">未充值</view>
      <view class="tab" :class="{active: activeTab === 'shipped'}" @click="switchTab('shipped')">已充值</view>
      <view class="tab" :class="{active: activeTab === 'success'}" @click="switchTab('success')">已到账</view>
      <view class="tab" :class="{active: activeTab === 'refund'}" @click="switchTab('refund')">售后/退款</view>
    </view>
    
    <!-- 搜索框 -->
    <!-- <view class="search-box">
      <view class="search-input">
        <image class="search-icon" src="/static/Images/shop/Search.png" mode="aspectFit"></image>
        <input type="text" placeholder="搜索商品名称/卡密/订单编号" v-model="searchKeyword" />
      </view>
      <view class="search-btn" @click="handleSearch">筛选</view>
    </view> -->
    
    <!-- 订单列表 -->
    <scroll-view 
      class="order-list" 
      scroll-y="true" 
      @scrolltolower="loadMore"
      lower-threshold="100"
    >
      <!-- 订单项 -->
      <view class="order-item" v-for="(item, index) in filteredOrderList" :key="index" @click="goToOrderDetail(item)">
        <view class="order-header">
          <view class="shop-info">
            <image class="shop-avatar" :src="item.shopAvatar || '/static/Images/shop/Avatar.png'" mode="aspectFit"></image>
            <text class="shop-name">{{ item.shopName }}</text>
          </view>
          <view class="order-status" :class="getStatusClass(item.status)">{{ item.status }}</view>
        </view>
        
        <view class="order-content">
          <image class="product-image" :src="item.productImage" mode="aspectFit"></image>
          <view class="product-info">
            <text class="product-name">{{ item.productName }}</text>
            <text class="product-price">¥{{ item.price }}</text>
          </view>
        </view>
        
        <view class="order-footer">
          <view class="order-time">{{ item.orderTime }}</view>
          <view class="order-actions">
            <!-- 操作按钮 -->
            <view class="operation-buttons">
              <button class="action-btn primary" v-show="item.status === '未充值'" @click.stop="viewOrderDetail(item)">立即充值</button>
              <button class="action-btn" v-show="item.status === '售后/退款'" @click.stop="viewRefundDetails(item)">退款详情</button>
              <button class="action-btn primary" v-show="['已完成', '售后/退款'].includes(item.status)" @click.stop="deleteOrder(item)">删除订单</button>
              <button class="action-btn" v-show="['未充值', '已充值', '已完成'].includes(item.status)" @click.stop="viewOrderDetail(item)">订单详情</button>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="load-more" v-if="filteredOrderList.length > 0">
        <view v-if="loading" class="loading-text">
          <text>加载中...</text>
        </view>
        <view v-else-if="!hasMore" class="no-more-text">
          <text>没有更多数据了</text>
        </view>
        <view v-else class="pull-up-text">
          <text>上拉加载更多</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredOrderList.length === 0">
      <image class="empty-icon" src="/static/Images/common/Zanwu.png" mode="aspectFit"></image>
      <text class="empty-text">暂无数据</text>
    </view>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
    
    <!-- 支付组件 -->
    <Goodsbuy 
      :visible="showPayModal" 
      :goodsInfo="currentPayGoods" 
      :accountNumber="currentAccountNumber"
      :orderId="currentPayOrder?.originalData?.id || currentPayOrder?.id || ''"
      @close="closePayModal" 
      @pay="handlePayConfirm" 
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { goodsApi, userApi } from '@/utils/api';
import { userStorage } from '@/utils/storage';
import Goodsbuy from '@/components/Goodsbuy.vue';

// 商品类型列表
const productTypes = [
  { label: '全部', value: 'all', type: 0 },
  { label: '话费订单', value: 'phone', type: 1 },
  { label: '权益订单', value: 'rights', type: 3 },
  { label: '卡密订单', value: 'card', type: 2 },
];

// 当前激活的商品类型
const activeProductType = ref('all');

// 当前激活的标签
const activeTab = ref('all');

// 搜索关键词
const searchKeyword = ref('');

// 路由参数
const routeParams = ref({
  type: '',
  status: ''
});

// 订单数据
const orderData = ref([]);
const loading = ref(false);
const userInfo = ref({});
const userNickname = ref('用户');

// 支付相关数据
const showPayModal = ref(false);
const currentPayGoods = ref({});
const currentAccountNumber = ref('');
const currentPayOrder = ref(null);

// 切换商品类型标签
const switchProductType = (type) => {
  activeProductType.value = type;
  // 切换商品类型时重新加载数据
  currentPage.value = 1;
  hasMore.value = true;
  fetchOrderList();
};

// 切换订单状态标签
const switchTab = (tab) => {
  activeTab.value = tab;
  // 切换标签时重新加载数据
  currentPage.value = 1;
  hasMore.value = true;
  fetchOrderList();
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 获取路由参数
const getRouteParams = () => {
  const pages = getCurrentPages();
  const currentPageInstance = pages[pages.length - 1];
  const options = currentPageInstance.options || {};
  
  routeParams.value = {
    type: options.type || '',
    status: options.status || ''
  };
  
  // 根据传入的status参数设置默认激活的标签
  const statusTabMap = {
    'pending_delivery': 'trading',    // 待发货 -> 交易中
    'pending_receipt': 'shipped',     // 待收货 -> 已发货
    'completed': 'success',           // 已完成 -> 交易成功
    'refund': 'refund'               // 退款/售后 -> 售后/退款
  };
  
  if (routeParams.value.status && statusTabMap[routeParams.value.status]) {
    activeTab.value = statusTabMap[routeParams.value.status];
  }
  
  console.log('获取到的路由参数:', routeParams.value);
  console.log('设置的默认标签:', activeTab.value);
};

// 分页相关数据
const currentPage = ref(1);
const hasMore = ref(true);

// 请求订单列表接口
const fetchOrderList = async (isLoadMore = false) => {
  if (loading.value) return;
  
  try {
    loading.value = true;
    if (!isLoadMore) {
      uni.showLoading({ title: '加载中...' });
    }
    
    // 将页面状态映射为新接口状态参数
    const statusMap = {
      'trading': 0,     // 未充值
      'shipped': 7,     // 已充值
      'success': 8,     // 已到账
      'refund': 9       // 售后/退款
    };
    
    let apiStatus = -1; // 默认全部
    if (activeTab.value !== 'all') {
      apiStatus = statusMap[activeTab.value] || 0;
    }
    
    // 获取当前选中商品类型的type值
    const currentProductType = productTypes.find(type => type.value === activeProductType.value);
    const typeParam = currentProductType ? currentProductType.type : 1; // 默认值为1
    
    // 调用新接口获取订单数据
    const params = {
      bus_status: apiStatus,
      type: typeParam,
      page: isLoadMore ? currentPage.value : 1,
      size: 10
    };
    
    console.log('/api/goods/findGrabOrderByUser接口参数:', params);
    const response = await goodsApi.findGrabOrderByUser(params);
    console.log('抢单订单列表接口响应:', response);
    
    // 处理接口返回的数据
    if (response && response.data) {
      orderData.value = response.data;
      
      // 将接口数据转换为页面需要的格式
      const newOrders = response.data.map(order => {
        // 获取第一个商品信息（如果有多个商品，这里只显示第一个）
        const firstGoods = order.list && order.list.length > 0 ? order.list[0] : {};
        
        // 新的状态映射
        const statusMap = {
          8: '已完成',
          9: '售后/退款',
          0: '未充值',
          7: '已充值'
        };
        
        // 使用响应式的用户昵称和头像
        const nickname = userNickname.value;
        const avatar = userInfo.value?.avatar || userInfo.value?.head_img || userInfo.value?.user_avatar || userInfo.value?.headimg || '/static/Images/touxiang/1.png';
        return {
          id: order.id,
          shopName: nickname,
          shopAvatar: avatar,
          status: statusMap[order.bus_status] || '未知状态',
          productName: firstGoods.goods_name || '商品名称',
          productImage: firstGoods.imgs && firstGoods.imgs.length > 0 ? firstGoods.imgs[0].trim() : '/static/Images/order/Product.png',
          price: order.bus_price || '0.00',
          orderTime: order.create_time ? new Date(order.create_time * 1000).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          }) : '',
          orderNo: order.order_no,
          originalData: order // 保存原始数据，方便后续使用
        };
      });
      
      // 分页处理
      if (isLoadMore) {
        orders.value = [...orders.value, ...newOrders];
      } else {
        orders.value = newOrders;
        currentPage.value = 1;
      }
      
      // 判断是否还有更多数据
      hasMore.value = newOrders.length >= 10;
      
      if (isLoadMore) {
        currentPage.value++;
      }
    }
    
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    console.error('获取订单列表失败:', error);
    uni.showToast({
      title: error.message || '获取订单失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  // 实现搜索逻辑
  console.log('搜索关键词:', searchKeyword.value);
  // 重新请求数据
  currentPage.value = 1;
  hasMore.value = true;
  fetchOrderList();
};

// 上拉加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return;
  fetchOrderList(true);
};

// 跳转到订单详情
const goToOrderDetail = (item) => {
  uni.navigateTo({
    url: `/pages/shop/orderdetail?id=${item.id}`
  });
};

// 查看订单详情
const viewOrderDetail = (item) => {
  uni.navigateTo({
    url: `/pages/order/billorderdetail?id=${item.id}`
  });
};



// 关闭支付弹窗
const closePayModal = () => {
  showPayModal.value = false;
  currentPayGoods.value = {};
  currentAccountNumber.value = '';
  currentPayOrder.value = null;
};

// 确认支付
const handlePayConfirm = (paymentData) => {
  console.log('=== orderlist.vue 支付确认调试信息 ===');
  console.log('完整支付数据:', paymentData);
  console.log('paymentData类型:', typeof paymentData);
  console.log('paymentData.response:', paymentData?.response);
  console.log('paymentData.response.msg:', paymentData?.response?.msg);
  console.log('当前订单:', currentPayOrder.value);
  console.log('======================================');
  
  // 显示支付接口返回的msg信息
  let toastTitle = '支付成功';
  if (paymentData && paymentData.response && paymentData.response.msg) {
    toastTitle = paymentData.response.msg;
    console.log('使用接口返回的msg:', toastTitle);
  } else {
    console.log('使用默认提示信息:', toastTitle);
  }
  
  uni.showToast({
    title: toastTitle,
    icon: 'success',
    duration: 2000
  });
  
  // 关闭支付弹窗
  closePayModal();
  
  // 延迟刷新订单列表，避免影响支付提示信息显示
  setTimeout(() => {
    fetchOrderList();
  }, 2500);
};

// 取消订单
const cancelOrder = (item) => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消该订单吗？',
    success: (res) => {
      if (res.confirm) {
        // 实现取消订单逻辑
        const index = orders.value.findIndex(order => order === item);
        if (index > -1) {
          orders.value[index].status = '已取消';
          
          uni.showToast({
            title: '订单已取消',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 确认收货
const confirmReceipt = (item) => {
  uni.showModal({
    title: '确认收货',
    content: '确定已收到商品吗？',
    success: (res) => {
      if (res.confirm) {
        // 实现确认收货逻辑
        const index = orders.value.findIndex(order => order === item);
        if (index > -1) {
          orders.value[index].status = '已完成';
          
          uni.showToast({
            title: '确认收货成功',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 再次购买
const buyAgain = (item) => {
  uni.showToast({
    title: '再次购买功能开发中',
    icon: 'none'
  });
};

// 申请售后
const applyAfterSale = (item) => {
  uni.showToast({
    title: '申请售后功能开发中',
    icon: 'none'
  });
};

// 删除订单
const deleteOrder = (item) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除该订单吗？删除后将无法恢复。',
    success: (res) => {
      if (res.confirm) {
        // 实现删除订单逻辑
        const index = orders.value.findIndex(order => order.id === item.id);
        if (index > -1) {
          orders.value.splice(index, 1);
          
          uni.showToast({
            title: '订单已删除',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 查看退款详情
const viewRefundDetails = (item) => {
  uni.navigateTo({
    url: `/pages/shop/refunddetails?id=${item.id}`
  });
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case '待充值':
      return 'status-trading';
    case '已充值':
      return 'status-shipped';
    case '已到账':
      return 'status-success';
    case '已放弃':
      return 'status-canceled';
    case '售后/退款':
      return 'status-refund';
    default:
      return '';
  }
};

// 订单数据（从接口获取）
const orders = ref([]);

// 根据当前标签、商品类型和搜索关键词过滤订单列表
const filteredOrderList = computed(() => {
  let orderList = orders.value;
  
  // 为订单添加商品类型属性（基于接口返回的type字段）
  orderList = orderList.map(order => {
    let productType = 'card'; // 默认为卡密类型
    
    // 根据原始数据中的type字段确定商品类型
    if (order.originalData && order.originalData.type) {
      const typeValue = order.originalData.type;
      if (typeValue === 1) {
        productType = 'phone'; // 话费充值
      } else if (typeValue === 3) {
        productType = 'rights'; // 权益充值
      } else if (typeValue === 2) {
        productType = 'card'; // 卡密充值
      }
    }
    
    return { ...order, productType };
  });
  
  // 根据商品类型筛选
  if (activeProductType.value !== 'all') {
    orderList = orderList.filter(order => order.productType === activeProductType.value);
  }
  
  // 根据订单状态标签筛选
  if (activeTab.value !== 'all') {
    const statusMap = {
      'trading': '未充值',     // 修正为与接口返回状态一致
      'shipped': '已充值',     // 修正为与接口返回状态一致
      'success': '已完成',
      'refund': '售后/退款'
    };
    
    orderList = orderList.filter(order => {
      if (activeTab.value === 'refund') {
        return order.status.includes('退款') || order.status.includes('售后');
      }
      return order.status === statusMap[activeTab.value];
    });
  }
  
  // 根据搜索关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    orderList = orderList.filter(order => {
      return order.productName.toLowerCase().includes(keyword) ||
             order.id.toLowerCase().includes(keyword);
    });
  }
  
  return orderList;
});

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const localUserInfo = userStorage.getUserInfo();
    if (localUserInfo && Object.keys(localUserInfo).length > 0) {
      userInfo.value = localUserInfo;
      userNickname.value = localUserInfo.nickname || localUserInfo.nick_name || localUserInfo.name || localUserInfo.username || '用户';
    } else {
      // 如果本地没有用户信息，可以调用API获取
      const response = await userApi.getUserInfo();
      if (response && response.data) {
        userInfo.value = response.data;
        userNickname.value = response.data.nickname || response.data.nick_name || response.data.name || response.data.username || '用户';
        userStorage.setUserInfo(response.data);
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 页面加载时初始化
onMounted(async () => {
  getRouteParams();
  await fetchUserInfo();
  fetchOrderList();
});

// 页面显示时刷新数据（uni-app 会自动调用）
const onShow = () => {
  // 重置分页状态
  currentPage.value = 1;
  hasMore.value = true;
  fetchOrderList();
};

// 注册页面生命周期
uni.addInterceptor('onShow', onShow);

// 注册组件
const components = {
  Goodsbuy
};
</script>

<style lang="scss">
.order-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-bottom: 30rpx;
}

/* 顶部导航栏 */
.shop-header {
  position: relative;
  width: 100%;
  background-color: #fff;
  z-index: 10;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 30rpx;
  padding-top: calc(var(--status-bar-height, 44px) + 20rpx);
  box-sizing: border-box;
}

.header-content {
  position: relative;
  z-index: 11;
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 750rpx;
}

.back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  left: 30rpx;
  z-index: 12;
  cursor: pointer;
  border-radius: 50%;
  background-color: transparent;
  transition: background-color 0.2s;
}

.back-btn:active {
  background-color: rgba(0, 0, 0, 0.1);
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  color: #222;
  font-size: 36rpx;
  font-weight: 500;
  text-align: center;
  width: 100%;
}



/* 商品类型标签 */
.product-type-tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-top: 8rpx;
  position: relative;
  overflow-x: auto;
  white-space: nowrap;
  border-bottom: 1rpx solid #f0f0f0;
  z-index: 9;
}

.type-tab {
  font-size: 28rpx;
  color: #666;
  margin-right: 40rpx;
  position: relative;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  background-color: #f5f5f5;
}

.type-tab.active {
  color: #fff;
  font-weight: 500;
  background-color: #ff4d4f;
}

/* 订单状态标签 */
.status-tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx 30rpx;
  position: relative;
  overflow-x: auto;
  white-space: nowrap;
  z-index: 9;
}

.tab {
  font-size: 28rpx;
  color: #666;
  margin-right: 40rpx;
  position: relative;
  padding-bottom: 10rpx;
}

.tab.active {
  color: #ff4d4f;
  font-weight: 500;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #ff4d4f;
  border-radius: 2rpx;
}

/* 搜索框 */
.search-box {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-top: 2rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.search-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.search-input input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
}

.search-btn {
  width: 120rpx;
  height: 1.8rem;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 28rpx;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
}

/* 订单列表 */
.order-list {
  padding: 20rpx 30rpx;
  height: calc(100vh - 400rpx); /* 设置固定高度以支持滚动 */
  box-sizing: border-box;
}

.order-item {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.shop-info {
  display: flex;
  align-items: center;
}

.shop-avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  margin-right: 10rpx;
}

.shop-name {
  font-size: 28rpx;
  color: #333;
}

.order-status {
  font-size: 28rpx;
  font-weight: 500;
}

.status-trading {
  color: #1890ff;
}

.status-shipped {
  color: #ff6b6b;
}

.status-success {
  color: #52c41a;
}

.status-canceled {
  color: #999;
}

.status-refund {
  color: #ff4d4f;
}

.order-content {
  display: flex;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 10rpx;
  background-color: #f5f5f5;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: 500;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-actions {
   display: flex;
  flex-direction: column;
  margin-top: 20rpx;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  margin-bottom: 20rpx;
  gap: 20rpx;
  min-height: 60rpx;
}

.action-btn {
  height: 60rpx;
  padding: 0 30rpx;
  background-color: #8f8e8e;
  border: none;
  color: #fff;
  font-size: 24rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;
  min-width: 120rpx;
  text-align: center;
}

.action-btn.primary {
  background-color: #ff4d4f;
  border: none;
  color: #fff;
}

/* 空状态 */
.empty-state {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 8;
}

.empty-icon {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  font-weight: 400;
  text-align: center;
}

/* 加载更多提示 */
.load-more {
  padding: 30rpx;
  text-align: center;
}

.loading-text,
.no-more-text,
.pull-up-text {
  font-size: 24rpx;
  color: #999;
}

.loading-text {
  color: #007aff;
}

.no-more-text {
  color: #ccc;
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
}
</style>